package com.atguigu.demojuc.chap03.sub;

/**
 * @author njg
 * @version 1.0
 * @date 2025/6/17 18:35
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * **案例**：
 *
 * 多线程之间按顺序调用，实现AA->BB->CC。三个线程启动，要求如下：
 *
 * AA打印5次，BB打印10次，CC打印15次
 *
 * 接着
 *
 * AA打印5次，BB打印10次，CC打印15次
 * 。。。打印10轮
 *
 * 分析实现方式：
 *
 * 1. 有一个锁Lock，3把钥匙Condition
 * 2. 有顺序通知（切换线程），需要有标识位
 * 3. 判断标志位
 * 4. 输出线程名 + 内容
 * 5. 修改标识符，通知下一个
 */
public class ThreadOrderAccess {
    private Integer flag = 1;

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();


    public void print5(){
          lock.lock();
            try
            {
                while (flag != 1){
                    condition1.await();
                }
                for (int i = 1; i <= 5; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "打印"+i+"次");
                }
                flag = 2;
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

    }
    public void print10(){
        lock.lock();
        try
        {
            while (flag != 2){
                condition2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "打印"+i+"次");
            }
            flag = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public void print15(){
        lock.lock();
        try
        {
            while (flag != 3){
                condition3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "打印"+i+"次");
            }
            flag = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public static void main(String[] args) {
        ThreadOrderAccess t = new ThreadOrderAccess();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                t.print5();
            }, "A").start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                t.print10();
            }, "B").start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                t.print15();
            }, "C").start();
        }
    }
}
